//切换壁纸
$(function (){
    const array = [
        ["https://yf-myblog.oss-cn-shenzhen.aliyuncs.com/public/blogArticles/2022-10-09/1665293410.jpeg","触摸云辉和星云"],
        ["https://yf-myblog.oss-cn-shenzhen.aliyuncs.com/public/blogArticles/2022-09-30/1664469042.jpeg","海洋小房子"],
        ["https://yf-myblog.oss-cn-shenzhen.aliyuncs.com/public/blogArticles/2022-11-06/1667702252.jpeg","撑伞和服女孩"],
        ["https://yf-myblog.oss-cn-shenzhen.aliyuncs.com/public/blogArticles/2022-10-09/1665294371.jpeg","粉色花与女孩"],
        ["https://yf-myblog.oss-cn-shenzhen.aliyuncs.com/public/blogArticles/2022-09-30/1664470028.jpeg","樱花树枝"],
        ["https://yf-myblog.oss-cn-shenzhen.aliyuncs.com/public/blogArticles/2022-09-30/1664469368.jpeg","绿草"],
        ["https://yf-myblog.oss-cn-shenzhen.aliyuncs.com/public/blogArticles/2022-10-09/1665289846.png","Pokemon"],
        ["https://yf-myblog.oss-cn-shenzhen.aliyuncs.com/public/blogArticles/2022-10-22/1666445081.jpeg","猫和蝴蝶"],
    ];
    let cookie = $.cookie('wallpaper');
    if (cookie===undefined){cookie=0;}
    $("body").append(
        "  <div class=\"background\" id=\"wallpaper\">\n" +
        "        <img src=\""+array[cookie][0]+"\">\n" +
        "    </div>" +
        " \n" +
        "<div class=\"am-modal am-modal-alert\" tabindex=\"-1\" id=\"wallpaper-box\">" +
        "<div class=\"am-modal-dialog\" style=\"height: 350px;border-radius: 10px;overflow-y: scroll;\">\n" +
        "    <span class=\"am-modal-btn am-icon-close\" style=\"float:right;font-size: 20px;line-height: 25px;height: 25px;border-radius: 15px;\" id=\"paperbox-close\"></span>\n" +
        "<div style=\"margin:0 auto;width: 83%;\">\n" +
        "    <div style=\"font-size: 20px;margin-top: 25px;width: 83%;height: 35px;\"><span style=\"float:left;\">更换壁纸</span></div>\n" +
        "<div style=\"height: 5px;width:83%;margin-top: 20px;\"><span style=\"float:left;font-size:13px;color: rgba(0,0,0,.6);\">自定义</span>\n" +
        "</div>\n" +
        "<div style=\"height: 100px;width:83%;margin-top: 20px;\">\n" +
        "<div style=\"width: 135px;height: 90px;background-color: rgba(0,0,0,.05);border-radius:10px;display: flex;justify-content: center;align-items: center;float: left;\">\n" +
        "    <span class=\"am-icon-photo am-icon-md\"></span>\n" +
        "</div>\n" +
        "    <div style=\"width: 240px;\"><span style=\"font-weight: bold;font-size: 15px;float:left;margin-left: 20px;\">上传壁纸</span>\n" +
        "<button type=\"button\" class=\"am-btn am-btn-success\" style=\"border-radius: 10px;margin-top: 16px;font-size: small;\">浏览..</button></div>\n" +
        "</div>\n" +
        "<div style=\"height: 5px;width:83%;margin-top: 20px;\"><span style=\"float:left;font-size:13px;color: rgba(0,0,0,.6);\">默认</span>\n" +
        "</div><div style=\"height: auto;width: 105%;margin-top: 20px;\">\n" +
        "    <div class=\"am-g\" id=\"wallpaper-fill\">\n" +
        "</div>\n" +
        "</div></div>\n" +
        "                \n" +
        "            </div> " +
        "</div>");
    //打开壁纸窗口填充壁纸
    for(let i=0;i<array.length;i++){
        let wallpaper_fill =  $("#wallpaper-fill");
        wallpaper_fill.append(
            "<div class=\"am-u-sm-4\" data-id=\""+i+"\" style=\"padding: 2px;float: left;height:80px;margin-bottom: 5px;\">\n" +
            "    <a href=\"javascript:void(0);\" class=\"am-thumbnail\" style=\"display:block;border:none;border-radius: 15px;\">\n" +
            "      <img src=\""+array[i][0]+"\" title=\""+array[i][1]+"\" style=\"border-radius: 10px;\">\n" +
            "    </a>\n" +
            "<div class='wallpaper-check'>\n" +
            "    <span class=\"am-icon-check\" style=\"font-size: 30px;color: white;\"></span>\n" +
            "</div>" +
            "  </div>" +
            "  </div>");
        if(i===parseInt($.cookie('wallpaper'))){
            $(".am-u-sm-4[data-id=" +i+"]").children("div").css("display","flex");
        }
    }
    $('#change_wallpaper').click(function (){
        console.log("切换壁纸");
        $("#wallpaper-box").modal();
        //弹出壁纸窗口把主窗口的滚动条锁定
        var scrollTop = $('body').scrollTop();
        $('body').css({"overflow":"hidden","position":"fixed","top": scrollTop*-1});
    });
    //鼠标移入时间，css动画
    $(document).on('mouseover',".am-u-sm-4",function (){
        let effect =  $(this);
        effect.addClass("am-animation-scale-up","am-animation-delay-3","am-animation-reverse");
        //设置1秒延时，关闭动画
        setTimeout(function (){
           effect.removeClass("am-animation-scale-up");
        },1000)
    });
    //点击事件，换壁纸
    $(document).on('click', ".am-u-sm-4", function () {
        let curr = $(this).attr("data-id");
        $("<div class=\"background\" id=\"wallpaper\">\n" +
            "        <img src=\""+array[$(this).attr("data-id")][0]+"\">\n" +
            "    </div>").replaceAll($("#wallpaper"));
        //切换选择的壁纸
        $(".am-u-sm-4[data-id=" +$.cookie("wallpaper")+"]").children("div").css("display","none");
        $(".am-u-sm-4[data-id=" +curr+"]").children("div").css("display","flex");
        //把换的壁纸存入COOKIE
        $.cookie('wallpaper',$(this).attr("data-id"), { expires: 7, path: '/' ,secure: false});

    });
    //壁纸盒子失去焦点后也恢复滚动条
    $('#wallpaper-box').blur(function (){
        $('body').css({"overflow":"auto","position":"static","top":"auto"});
    });
    //关闭壁纸窗口恢复滚动条
    $('#paperbox-close').click(function (){
        //弹出框关闭后设置回来
        $('body').css({"overflow":"auto","position":"static","top":"auto"});
    });
    // $.ajax({
    //     url:'/wallpaper',
    //     dataType:'JSON',
    //     type:"GET",
    //     success:function(data){
    //         const array = [];
    //         for(let i = 0;i<data.length;i++){
    //             //遍历JSON字符串转换成吗Map
    //             array[i] = new Map(Object.entries(data[i]));
    //         }
    //         // console.log(array[0].get("url"));
    //         let i = Math.floor(Math.random()*array.length+1);//1-array.length随机数
    //         $("body").append("  <div class=\"background\" id=\"wallpaper\">\n" +
    //             "        <img src=\""+array[i-1].get("url")+"\">\n" +
    //             "    </div>");
    //         $('#change_wallpaper').click(function (){
    //             console.log("切换壁纸");
    //             let j = Math.floor(Math.random()*array.length+1);//1-array.length随机数
    //             $("<div class=\"background\" id=\"wallpaper\">\n" +
    //                 "        <img src=\""+array[j-1].get("url")+"\">\n" +
    //                 "    </div>").replaceAll($("#wallpaper"));
    //         })
    //     },
    //     error:function(){
    //         alert("壁纸请求失败")}
    // });
});
// 失败消息盒
function dangerNotice(notice) {
    $('.dangerNotice').html(notice);
    $('.dangerNoticeAlert').css("display","block");
    var closeNoticeBox = setTimeout(function () {
        $('.dangerNoticeAlert').css("display","none");
    },3000);
}
// 成功消息盒
function successNotice(notice) {
    $('.successNotice').html(notice);
    $('.successNoticeAlert').css("display","block");
    var closeNoticeBox = setTimeout(function () {
        $('.successNoticeAlert').css("display","none");
    },3000);
}
//设置右侧栏箭头动画显示
var sidebar_toggle = $("#sidebar_toggle");
var sidebar_toggle_line_first = $(".sidebar-toggle-line-first");
var sidebar_toggle_line_middle = $(".sidebar-toggle-line-middle");
var sidebar_toggle_line_last = $(".sidebar-toggle-line-last");
sidebar_toggle.mouseenter(function () {
    sidebar_toggle_line_first.animate({
        width:'50%',
        top:'2px',
        left:'0px'
    },function () {
        sidebar_toggle_line_first.css({
            'transform':'rotate(-45deg)',
            'transition':'transform 0.5',
            'width':'50%',
            'top':'2px',
            'left':'0px'
        })
    });
    sidebar_toggle_line_middle.animate({
        width:'90%',
        top:'0px',
        left:'0px'
    },function () {
        sidebar_toggle_line_middle.css({
            'transform':'rotate(0deg)',
            'transition':'transform 0.5',
            'width':'90%',
            'top':'0px',
            'left':'0px'
        })
    });
    sidebar_toggle_line_last.animate({
        width:'50%',
        top:'-2px',
        left:'0px'
    },function () {
        sidebar_toggle_line_last.css({
            'transform':'rotate(45deg)',
            'transition':'transform 0.5, width 0.5',
            'width':'50%',
            'top':'-2px',
            'left':'0px'
        })
    })
});
sidebar_toggle.mouseleave(function () {
    sidebar_toggle_line_first.animate({
        top:'0px',
        left:'0px'
    },function () {
        sidebar_toggle_line_first.css({
            'transform':'rotateZ(0deg)',
            'transition':'transform 0.5, width 0.5',
            'width':'100%',
            'top':'0px',
            'left':'0px'
        })
    });
    sidebar_toggle_line_middle.animate({
        top:'0px',
        left:'0px'
    },function () {
        sidebar_toggle_line_middle.css({
            'transform':'rotateZ(0deg)',
            'transition':'transform 0.5, width 0.5',
            'width':'100%',
            'top':'0px',
            'left':'0px'
        })
    });
    sidebar_toggle_line_last.animate({
        top:'-0px',
        left:'0px'
    },function () {
        sidebar_toggle_line_last.css({
            'transform':'rotateZ(0deg)',
            'transition':'transform 0.5',
            'width':'100%',
            'top':'-0px',
            'left':'0px'
        })
    })
});

//获得访客量，除文章显示界面外其他界面访客量通用
var pageName = window.location.pathname + window.location.search;
$.ajax({
    type:'get',
    url:'/getVisitorNumByPageName',
    dataType:'json',
    data:{
        pageName:pageName.substring(1)
    },
    success:function (data) {
        if(data['status'] == 103){
            $("#totalVisitors").html(0);
            $("#visitorVolume").html(0);
        } else {
            $("#totalVisitors").html(data['data']['totalVisitor']);
            $("#visitorVolume").html(data['data']['pageVisitor']);
        }
    },
    error:function () {
    }
});

//点击右侧栏获得日志、分类、标签数目以及微信公众号图片
$('#sidebar_toggle').click(function () {
    $.ajax({
        type:'get',
        url:'/findArchivesCategoriesTagsNum',
        dataType:'json',
        data:{
        },
        success:function (data) {
            if(data['status'] == 103){
                dangerNotice(data['message'] + " 获得右侧栏信息失败")
            } else {
                $('.archivesNum').html(data['data']['archivesNum']);
                $('.categoriesNum').html(data['data']['categoriesNum']);
                $('.tagsNum').html(data['data']['tagsNum']);
            }
        },
        error:function () {
        }
    });
    $('.weixinPublic').attr("src","img/wx.jpg");
});

//获得登录用户未读消息
$.ajax({
    type:'post',
    url:'/getUserNews',
    dataType:'json',
    data:{
    },
    success:function (data) {
        var thisPageName = window.location.pathname + window.location.search;
        var news = $('.news');
        if(data['status'] == 103){
            return;
        }
        if(data['status'] != 101 && data['data']['result'] != 0){
            news.append($('<span class="newsNum am-badge am-badge-danger am-round">' + data['data']['result']['allNewsNum'] + '</span>'));
            if(thisPageName === "/user"){
                if(data['data']['result']['commentNum'] !== 0){
                    $('.commentMessage').find('a').append($('<span class="commentNotReadNum am-margin-right am-fr am-badge am-badge-danger am-round">' + data['data']['result']['commentNum'] + '</span>'));
                }
                if(data['data']['result']['leaveMessageNum'] !== 0){
                    $('.leaveWord').find('a').append($('<span class="leaveMessageNotReadNum am-margin-right am-fr am-badge am-badge-danger am-round">' + data['data']['result']['leaveMessageNum'] + '</span>'));
                }
            }
        }
    },
    error:function () {
    }
});

//反馈
$('.feedbackClick').click(function () {
    $('.feedback').css("display","block")
});
$('.feedbackClose').click(function () {
    $('.feedback').css("display","none")
});
$('.feedbackFormBtn').click(function () {
    var feedbackFormContent = $('#feedbackFormContent');
    var feedbackFormQQ = $('.feedbackFormQQ');
    if(feedbackFormContent.val().length == 0){
        dangerNotice("反馈内容不能为空哦！")
    } else {
        $.ajax({
            type:'POST',
            url:'/submitFeedback',
            dataType:'json',
            data:{
                feedbackContent:feedbackFormContent.val(),
                contactInfo:feedbackFormQQ.val()
            },
            success:function (data) {
                if(data['status'] == 101){
                    $.get("/toLogin",function(data,status,xhr){
                        window.location.replace("/login");
                    });
                } else if (data['status'] == 103){
                    dangerNotice(data['message'] + " 反馈失败")
                }
                else {
                    successNotice("反馈成功，我会尽快解决的！");
                    $('.feedback').css("display","none");
                }
            },
            error:function () {
            }
        });
    }
});


//图片懒加载
$(function() {
    // 获取window的引用:
    var $window = $(window);
    // 获取包含data-src属性的img，并以jQuery对象存入数组:
    var lazyImgs = _.map($('img[data-src]').get(), function (i) {
        return $(i);
    });
    // 定义事件函数:
    var onScroll = function () {
        // 获取页面滚动的高度:
        var wtop = $window.scrollTop();
        // 判断是否还有未加载的img:
        if (lazyImgs.length > 0) {
            // 获取可视区域高度:
            var wheight = $window.height();
            // 存放待删除的索引:
            var loadedIndex = [];
            // 循环处理数组的每个img元素:
            _.each(lazyImgs, function ($i, index) {
                // 判断是否在可视范围内:
                if ($i.offset().top - wtop - 350 < wheight) {
                    // 设置src属性:
                    $i.attr('src', $i.attr('data-src'));
                    // 添加到待删除数组:
                    loadedIndex.unshift(index);
                }
            });
            // 删除已处理的对象:
            _.each(loadedIndex, function (index) {
                lazyImgs.splice(index, 1);
            });
        }
    };
    // 绑定事件:
    $window.scroll(onScroll);
    // 手动触发一次:
    onScroll();
});
